<template>
    <div>
        <Card style="width:100%" class="detail-content-layout mb16">
            <template #title>
                {{ $t('需求起草') }}
            </template>
            <template #extra>
                <div class="h-arrow-wrap" @click="toggle = !toggle">
                    <i :class="{toggleActive:toggle}" class="iconfont zy-common-jiantou h-arrow-icon"></i>
                </div>
            </template>
            <transition name="slide-up">
                <div v-if="toggle">
                    <Form ref="form" :model="form" :rules="rules" label-position="top">
                        <Row :gutter="24">
                            <Col span="6">
                                <FormItem :label="$t('项目ID')" prop="projectId">
                                    <Input maxlength="255" :disabled="disabled" clearable type="text"
                                           v-model="form.projectId"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem :label="$t('项目名称')" prop="projectName">
                                    <Input maxlength="255" :disabled="disabled" clearable type="text"
                                           v-model="form.projectName"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem :label="$t('项目类型')" prop="projectType">
                                    <Select
                                        transfer
                                        :disabled="disabled"
                                        v-model="form.projectType"
                                        filterable
                                        clearable
                                        :placeholder="`${$t('common.selectInfo')}`"
                                    >
                                        <Option v-for="(item,index) in projectTypeList" :key="index" :value="item.value"
                                                :label="item.label"></Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="OPM" prop="factoryOwner" required>
                                    <!--                <Input :disabled="disabled" clearable type="text" v-model="form.factoryOwner"-->
                                    <!--                       :placeholder="$t('请输入')"></Input>-->
                                    <Select
                                        transfer
                                        v-if="!disabled"
                                        :disabled="disabled"
                                        v-model="form.factoryOwner"
                                        filterable
                                        clearable
                                        :remote-method="searchUserList"
                                        :placeholder="`${$t('common.selectInfo')}`"
                                    >
                                        <Option v-for="(item,index) in userList" :key="index" :value="item.id"
                                                :label="item.realname"></Option>
                                    </Select>
                                    <Input v-else disabled clearable type="text" v-model="form.factoryOwnerName"
                                           :placeholder="$t('请输入')"/>
                                </FormItem>
                            </Col>


                            <Col span="6">
                                <FormItem :label="$t('地址')" prop="companyId" required>
                                    <Select
                                        transfer
                                        v-if="!disabled"
                                        v-model="form.companyId"
                                        filterable
                                        clearable
                                        :disabled="disabled"
                                        :placeholder="`${$t('common.selectInfo')}`"
                                    >
                                        <Option
                                            v-for="(item, index) of companyList"
                                            :value="item.value"
                                            :key="index"
                                            :label="item.label"
                                        />
                                    </Select>
                                    <Input v-else disabled clearable type="text" v-model="form.companyName"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem :label="$t('工厂')" prop="orgId" required>
                                    <!--                <Cascader v-if="!disabled" :disabled="disabled" ref="Cascader" clearable :data="orgList"-->
                                    <!--                          v-model="form.orgId"-->
                                    <!--                          :placeholder="`${$t('common.selectInfo')}`" change-on-select></Cascader>-->
                                    <Select
                                        transfer
                                        v-if="!disabled"
                                        v-model="form.orgId"
                                        clearable
                                        @on-change="orgChange"
                                        :label-in-value="true"
                                        :disabled="disabled"
                                        :placeholder="`${$t('common.selectInfo')}`"
                                    >
                                        <Option
                                            v-for="(item, index) of orgList"
                                            :value="item.id"
                                            :key="index"
                                            :label="item.name"
                                            :tag="item.code"
                                        />
                                    </Select>
                                    <Input v-else disabled clearable type="text" v-model="form.orgName"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem :label="$t('项目负责人')">
                                    <Input disabled clearable type="text" v-model="form.projectOwnerStr"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem :label="$t('预算范围')" prop="budgetReach">
                                    <Select
                                        transfer
                                        v-model="form.budgetReach"
                                        clearable
                                        :label-in-value="true"
                                        :disabled="disabled"
                                        :placeholder="`${$t('common.selectInfo')}`"
                                    >
                                        <Option
                                            v-for="(item, index) of budgetList"
                                            :value="item.value"
                                            :key="index"
                                            :label="item.label"
                                        />
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem :label="$t('注释1')" prop="description">
                                    <Input maxlength="200" :disabled="disabled" clearable type="text"
                                           v-model="form.description"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6" v-if="disabled">
                                <FormItem :label="$t('提交人')">
                                    <Input disabled clearable type="text" v-model="form.submitByStr"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6" v-if="disabled">
                                <FormItem :label="$t('提交时间')">
                                    <Input disabled clearable type="text" v-model="form.submitTime"
                                           :placeholder="$t('请输入')"></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem prop="bdgAmount">
                                    <InputNumber max="999999999"
                                                 :disabled="disabled"
                                                 clearable
                                                 v-model="form.bdgAmount"
                                                 :placeholder="$t('请输入')"
                                                 :formatter="value => `k￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                                 :parser="value => value.replace(/k\￥\s?|(,*)/g, '')"
                                                 @on-change="bdgAmountChange"
                                    >
                                    </InputNumber>
                                    <div slot="label" style="display: inline-block">
                                        {{ $t('预算金额') }}
                                        <Tooltip placement="top-start" max-width="200"
                                                 content="预算金额小于€50,000时，需GM审批；除此之外还需要Global MS Manager、Global MS Director和SVP审批。">
                                            <Icon type="md-information-circle"/>
                                        </Tooltip>
                                    </div>
                                </FormItem>
                            </Col>
                            <Col span="6" style="height: 79px">
                                <FormItem :label="$t('该项目是否包括在资本预算中')" prop="exceedsBudget">
                                    <RadioGroup v-model="form.exceedsBudget" :disabled="disabled">
                                        <Radio :disabled="disabled" :label=1>{{ $t('是') }}</Radio>
                                        <Radio :disabled="disabled" :label=0>{{ $t('否') }}</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </Col>
                            <Col span="6" style="height: 79px">
                                <FormItem :label="$t('是否需要计算预计收益')" prop="whetherEstimatedBenefits" required>
                                    <RadioGroup v-model="form.whetherEstimatedBenefits" :disabled="disabled" @on-change="whetherEstimatedBenefitsChange">
                                        <Radio :disabled="disabled" :label=1>{{ $t('是') }}</Radio>
                                        <Radio :disabled="disabled" :label=2>{{ $t('否') }}</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </Col>
                            <!--                            <Col span="6">-->
                            <!--                                <FormItem :label="$t('预计收益')" prop="estimatedBenefits"-->
                            <!--                                          :required="form.whetherEstimatedBenefits==1">-->
                            <!--                                    <InputNumber max="999999999" :disabled="disabled" clearable-->
                            <!--                                                 v-model="form.estimatedBenefits"-->
                            <!--                                                 :placeholder="$t('请输入')"-->
                            <!--                                                 :formatter="value => `k￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"-->
                            <!--                                                 :parser="value => value.replace(/k\￥\s?|(,*)/g, '')">-->
                            <!--                                    </InputNumber>-->
                            <!--                                </FormItem>-->
                            <!--                            </Col>-->
                            <Col span="6">
                                <FormItem :label="$t('估计的投资回报率')" :required="form.whetherEstimatedBenefits==1">
                                    <Input maxlength="10" disabled clearable type="text"
                                           v-model="form.returnOnInvestment"
                                           :placeholder="$t('请输入')">
                                        <template #append>
                                            <span>{{ $t('年') }}</span>
                                        </template>
                                    </Input>
                                </FormItem>
                            </Col>
                            <Col span="6" style="height: 79px">
                                <FormItem :label="$t('包括子项目')" prop="includeSubProjects">
                                    <RadioGroup v-model="form.includeSubProjects" @on-change="includeSubProjectsChange"
                                                :disabled="((info.includeSubProjects==1 || info.orderProcessStatus==1) && info.displayButton!=1) || info.progressCode">
                                        <Radio
                                            :disabled="((info.includeSubProjects==1 || info.orderProcessStatus==1) && info.displayButton!=1) || info.progressCode"
                                            :label=1>{{ $t('是') }}
                                        </Radio>
                                        <Radio
                                            :disabled="((info.includeSubProjects==1 || info.orderProcessStatus==1) && info.displayButton!=1) || info.progressCode"
                                            :label=0>{{ $t('否') }}
                                        </Radio>
                                    </RadioGroup>
                                </FormItem>
                            </Col>
                            <Col span="6" v-if="!disabled">

                            </Col>
                            <Col span="6" v-if="!disabled">

                            </Col>
                            <Col span="6" class="autoHeight">
                                <FormItem :label="$t('规格说明书')" prop="specifications">
                                    <uploadFile ref="upload1" accept=".doc,.docx,.pdf" key="55"
                                                :fileList="info.specifications"
                                                :disabled="disabled"
                                                @change="(list)=>{form.specifications = list;}"/>
                                </FormItem>
                            </Col>
                            <Col span="6" class="autoHeight">
                                <FormItem :label="$t('商业案例')" prop="businessCases"
                                          :required="form.whetherEstimatedBenefits==1">
                                    <uploadFile ref="upload3" accept=".pdf,.xls,.xlsx,.ppt,.pptx" key="66"
                                                :fileList="info.businessCases"
                                                :disabled="disabled"
                                                @change="(list)=>{form.businessCases = list}"/>
                                </FormItem>
                            </Col>
                            <Col span="6" class="autoHeight" prop="otherAttachments">
                                <FormItem :label="$t('其他附件')">
                                    <uploadFile ref="upload2" key="77" :fileList="info.otherAttachments"
                                                :disabled="disabled"
                                                @change="(list)=>{form.otherAttachments = list}"/>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <rejectInfo :rejectFlows="rejectFlows"/>
                    <estimatedRevenueTable @change="estimatedRevenueChange" :disabled="disabled"
                                           :bdgAmount.sync="form.bdgAmount" ref="estimatedRevenueTable"
                                           :list="info.cvEstimateds" v-if="form.whetherEstimatedBenefits==1"/>
                    <div class="tableContent" v-if="form.includeSubProjects==1">
                        <p class="sub-title">{{$t('子项目')}}</p>
                        <Table class="resizable-table" @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,this.customCacheKeySpecIn)}" :columns="columns" :data="dataSource" border>
                            <template slot-scope="{ row,index }" slot="action">
<!--                                /&& row.editFlag!=0-->
                                <div class="ivu-table-cell-slot"
                                     v-if="info.orderProcessStatus!=1 && info.displayButton==0">
                                    <span class="operationBtn" v-if="row.operation ==='action'"
                                          @click="addItem">{{ $t('新增') }}</span>
                                    <span v-if="row.operation !=='action'" class="operationBtn"
                                          @click="removeItem(index)">{{ $t('删除') }}</span>
                                    <span v-if="row.operation !=='action' && !row.edit "
                                          class="operationBtn"
                                          @click="editItem(index)">{{ row.edit ? $t('更新') : $t('编辑') }}</span>
                                    <span v-if="row.operation !=='action' && row.edit "
                                          class="operationBtn"
                                          @click="saveItem(index)">{{ $t('提交') }}</span>
                                    <span v-if="row.operation !=='action' && row.edit  "
                                          class="operationBtn"
                                          @click="cancelSaveItem(index)">{{ $t('取消') }}</span>
                                </div>
                            </template>
                            <template slot-scope="{ row,index }" slot="amount">
                                <!--                <Input type="number" :key="index" @on-change="amountChange"-->
                                <!--                       v-model.number.trim="dataSource[index].subAmount" :placeholder="$t('请输入')"-->
                                <!--                       v-if="row.operation !=='action' && row.edit"/>-->

                                <InputNumber
                                    @on-change="amountChange"
                                    class="prependMoneyIcon tableInputNumberbr"
                                    style="width: 100%" max="999999999"
                                    clearable type="number"
                                    number
                                    v-if="row.operation !=='action' && row.edit"
                                    v-model.number="dataSource[index].subAmount"
                                    :placeholder="$t('请输入')"
                                    :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                    :parser="value => value.replace(/k\￥\s?|(,*)/g, '')"/>

                                <p style="text-align: left" v-else :class="{exceed:getCalcAmount()}">
                                    k￥{{ dataSource[index].subAmount | thousandth }}</p>
                            </template>
                            <template slot-scope="{ row,index }" slot="desc">
                                <Input v-model.trim="dataSource[index].subDescription" :placeholder="$t('请输入')"
                                       v-if="row.operation !=='action'  && row.edit"/>
                                <p style="text-align: left" v-else>{{ dataSource[index].subDescription }}</p>
                            </template>
                            <template slot-scope="{ row }" slot="projectId">
                                <div style="text-align: left" class="ellipsis" v-if="row.operation !=='action'" >{{ form.projectId }}</div>
                                <div style="text-align: left" v-else>{{ $t('总计') }}</div>
                            </template>
                            <template slot-scope="{ row }" slot="subProjectId">
                                <p style="text-align: left" class="ellipsis" v-if="row.operation !=='action'">
                                    {{ form.projectId }}-{{ row.subProjectId }}
                                </p>
                            </template>
                        </Table>
                    </div>
                    <subWarnModalTitle ref="subWarnModalTitle" @change="subWarnModalTitleChange"/>
                </div>
            </transition>
        </Card>
<!--        <bdgApprovalReject :info="info"/>&lt;!&ndash;&ndash;&gt;-->
    </div>
</template>

<script>
import uploadFile from "@/views/devBasic/capex/components/uploadFile";
import mixins from './mixins'
// import recursion from "@/util/recursion";
import rejectInfo from "@/views/devBasic/capex/components/rejectInfo";
import estimatedRevenueTable from "@/views/devBasic/capex/components/estimatedRevenueTable";

const totalComlums = {projectId: "总计", subAmount: 0, subDescription: "", operation: "action", id: ""}
import subWarnModalTitle from "@/views/devBasic/capex/components/subWarnModalTitle";
// import bdgApprovalReject from "@/views/devBasic/capex/components/bdgApprovalReject";

export default {
    name: "specIn",
    components: {uploadFile, rejectInfo, subWarnModalTitle, estimatedRevenueTable},
    mixins: [mixins],
    props: {
        info: {
            type: Object,
            default: () => {
            }
        },
        disabled: {
            type: Boolean,
            default: false
        },
        approvalInfo: {
            type: Object,
            default: () => {
            }
        },
        rejectFlows: {
            type: Object,
            default: () => {
            }
        },
        currentKey: {
            type: String,
            default: ""
        }
    },
    data() {
        const validateFile1 = (rule, value, callback) => {
            if (!(Array.isArray(this.form.specifications) && this.form.specifications.length > 0)) {
                callback(new Error(this.$t('请上传附件')));
            } else {
                callback();
            }
        };
        const validateFile2 = (rule, value, callback) => {
            if (!(Array.isArray(this.form.businessCases) && this.form.businessCases.length > 0) && this.form.whetherEstimatedBenefits==1) {
                callback(new Error(this.$t('请上传附件')));
            } else {
                callback();
            }
        };
        const validateOrg = (rule, value, callback) => {
            if (!value) {
                callback(new Error(this.$t('请选择')));
            } else {
                callback();
            }
        };
        const validateInput = (rule, value, callback) => {
            if (!value) {
                callback(new Error(this.$t('请输入')));
            } else {
                callback();
            }
        };
        const validateInputEstimatedBenefits = (rule, value, callback) => {
            if (!value && (this.form.whetherEstimatedBenefits == 1)) {
                callback(new Error(this.$t('请输入')));
            } else {
                callback();
            }
        };
        const whetherEstimatedBenefitsRules = (rule, value, callback) => {
            if (!value) {
                callback(new Error(this.$t('请选择')));
            } else {
                callback();
            }
        };
        return {
            toggle: true,
            form: {
                projectType: "",
                biddingIsRequired: 1,
                estimatedBenefits: "",
                exceedsBudget: 1,
                includeSubProjects: 0,
                projectName: "",
                orgId: "",
                companyId: "",
                bdgAmount: "",
                projectId: "",
                budgetReach: "",
                factoryOwner: "",
                whetherEstimatedBenefits: ""
            },

            orgList: [],
            rules: {
                projectId: [{required: true, type: "string", message: this.$t('请输入'), trigger: 'blur'}],
                projectName: [{required: true, type: "string", message: this.$t('请输入'), trigger: 'blur'},
                    {required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}
                ],
                projectType: [{required: true, type: "number", message: this.$t('请选择'), trigger: 'change'}],
                companyId: [{validator: validateOrg, trigger: 'change'}],
                orgId: [{validator: validateOrg, trigger: 'change'}],
                specifications: [{required: true, validator: validateFile1, trigger: 'change'}],
                businessCases: [{required: false, validator: validateFile2, trigger: 'change'}],
                // biddingIsRequired: [{required: true, type: "number", message: this.$t('请选择'), trigger: 'change'}],
                includeSubProjects: [{required: true, type: "number", message: this.$t('请选择'), trigger: 'change'}],
                bdgAmount: [{required: true, trigger: 'change', validator: validateInput}],
                exceedsBudget: [{required: true, type: "number", message: this.$t('请选择'), trigger: 'change'}],
                estimatedBenefits: [{trigger: 'change', validator: validateInputEstimatedBenefits}, {
                    trigger: 'blur',
                    validator: validateInputEstimatedBenefits
                }],
                factoryOwner: [{validator: validateOrg, trigger: 'change'}],
                budgetReach: [{required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}],
                whetherEstimatedBenefits: [{trigger: 'change', validator: whetherEstimatedBenefitsRules}],
            },
            columns: [
                {
                    title: this.$t('项目ID'),
                    key: 'projectId',
                    slot: "projectId",
                    resizable: true,tooltip: true,
                    tooltip: true
                },
                {
                    title: this.$t('子项目'),
                    key: 'subProjectId',
                    slot: "subProjectId",
                    resizable: true,tooltip: true,
                    tooltip:true
                },
                {
                    title: this.$t('预算金额'),
                    key: 'subAmount',
                    slot: "amount",
                    resizable: true,tooltip: true,
                    tooltip:true,
                    renderHeader: (h) => {
                        return h('div', [
                            h('span', {
                                domProps: {
                                    innerHTML: this.$t('预算金额')
                                },
                                attrs: {
                                    class: "required "
                                }
                            }),
                        ])
                    }
                },
                {
                    title: this.$t('描述'),
                    key: 'subDescription',
                    slot: "desc",
                    resizable: true,tooltip: true,
                    tooltip:true,
                    renderHeader: (h) => {
                        return h('div', [
                            h('span', {
                                domProps: {
                                    innerHTML: this.$t('描述')
                                },
                                attrs: {
                                    class: "required "
                                }
                            }),
                        ])
                    }
                },
                {
                    title: this.$t('操作'),
                    key: 'operation',
                    slot: "action",
                    width: this.util.autoWidth(200, 300),
                    align: "center"
                }
            ],

            dataSource: [{...totalComlums}],
            copyDataSource: [],
            activeIndex: 0,
            isExceed: false,
            userList: [],
            lastForm: {},
            isHandleSubProject: false,
            customCacheKeySpecIn:"customCacheKeySpecInSubItem"
        }
    },
    async created() {
        this.form.whetherEstimatedBenefits = 2

        this.getColumnWidth(this.columns,this.customCacheKeySpecIn)
        if (!this.disabled) {
            this.orgList = await this.getDeptList()
            this.form.submitByStr = this.userName
            this.form.projectOwnerStr = this.userName
            this.$forceUpdate()
        }
        if (Array.isArray(this.info.capexSubmitPos) && this.info.capexSubmitPos.length > 0) {
            const list = this.info.capexSubmitPos.map(item => {
                item.subAmount = item.bdgAmount
                item.subDescription = item.description
                item.subProjectId = item.projectId
                item.edit = false
                item.editStatus = true
                item.editStatus = true
                return item;
            })

            list.push(totalComlums)
            this.dataSource = JSON.parse(JSON.stringify(list))
        }

        if (this.info.projectId) {
            this.getForm(this.approvalInfo)
        }
        this.amountChange()
        // if (this.disabled) {
        //
        // } else {
        //   this.orgList = await this.getDeptList()
        //   if (Object.keys(this.rejectFlows).length > 0) {
        //     this.getForm(this.approvalInfo)
        //   }
        // }
    },
    methods: {
        whetherEstimatedBenefitsChange(value){
           if (value==2){
               this.form.returnOnInvestment = 0
           }
        },
        bdgAmountChange(value) {
            if (this.form.whetherEstimatedBenefits == 1)
                this.$refs.estimatedRevenueTable.calculatingBack(value)
        },
        estimatedRevenueChange(value) {
            this.form.returnOnInvestment = value
            this.$forceUpdate()
        },
        getAmountValue(v1, v2) {
            if (!v1 || !v2) {
                return 0
            } else {
                return (v1 / v2).toFixed(2)
            }
        },
        searchUserList(query) {
            this.axios({
                method: 'get',
                url: '/dms/user/userList',
                params: {key: query}
            }).then(res => {
                if (res.code === 200) {
                    this.userList = res.data
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        formatNum(num) {
            if (num === null) {
                return 0;
            }
            let value = num + "";
            value = value.replace(/,/g, "");
            if (/^[1-9]\d*$/.test(value)) {
                value = value.replace(/(?=(?!\b)(?:\d{3})+(?!\d))/g, ",");
            }

            if (value.includes(".")) {
                let tempArr = value.split(".");
                if (Array.isArray(tempArr) && tempArr.length === 2) {
                    const tempStr = tempArr[0].replace(
                        /(?=(?!\b)(?:\d{3})+(?!\d))/g,
                        ","
                    );
                    value = tempStr + "." + tempArr[1];
                }
            }

            return value;
        },
        includeSubProjectsChange(val) {
            if (val == 1) {
                if (this.dataSource.length === 1) {
                    this.dataSource.unshift({
                        id: 1,
                        subProjectId: 1,
                        subAmount: this.form.bdgAmount,
                        subDescription: "",
                        projectId: this.form.projectId,
                        edit: true
                    })
                }
            } else {
                // this.form.includeSubProjects = 1/
                if (this.checkEditStatus()) return false
            }
            this.amountChange()
            this.$forceUpdate()
        },
        subWarnModalTitleChange(index) {
            if (index == 1) {
                this.$refs.upload1.clearFiles()
                this.$refs.upload2.clearFiles()
                this.$refs.upload3.clearFiles()
            }
            this.form.bdgAmount = this.dataSource[this.dataSource.length - 1].subAmount / 1;
            this.dataSource[this.activeIndex]['edit'] = false
            this.submitSubProject()
            this.$forceUpdate()
        },
        getCalcAmount() {
            const status = this.dataSource[this.dataSource.length - 1].subAmount > (this.form.bdgAmount || 0)
            return status
        },
        checkEditStatus() {
            const obj = this.dataSource.find(item => item.edit === true)
            const status = obj ? true : false
            if (status) {
                this.$Message.error(this.$t('请保存子项目'))
            }
            return status
        },
        // checkAmountStatus() {
        //   const {progressCode, progressStatus} = this.info;
        //
        //   if (!progressCode && !progressStatus && this.getCalcAmount()) {
        //     this.$refs.subWarnModalTitle.showModal(1)
        //     return false;
        //   }
        //
        //   if (this.currentKey === 'BDG Approval' && this.getCalcAmount()) {
        //     this.$refs.subWarnModalTitle.showModal(2)
        //     return false;
        //   }
        //   if (Array.isArray(this.info.bdgApprovalInfos) && !this.info.bdgApprovalInfos.find(item => item.status === 0) && this.getCalcAmount()) {
        //     this.$refs.subWarnModalTitle.showModal(3)
        //     return false;
        //   }
        // },
        saveItem(index) {

            this.activeIndex = index

            if (!this.dataSource[this.activeIndex].subAmount) {
                this.$Message.error(this.$t('金额不能为空'))
                return;
            }

            if (!this.dataSource[this.activeIndex].subDescription) {
                this.$Message.error(this.$t('描述不能为空'))
                return;
            }


            // if (this.checkAmountStatus() === false) {
            //   return false
            // }
            this.amountChange()
            this.$forceUpdate()

            // if (this)
            if (this.info.reSetSpecIn == 1) {
                this.isHandleSubProject = true
            }

            const subAmount = this.dataSource[this.dataSource.length - 1].subAmount / 1
            if(this.form.bdgAmount < subAmount){
                this.form.bdgAmount = subAmount;
            }

            this.submitSubProject()
        },
        cancelSaveItem(index) {
            const obj = this.copyDataSource.find(item => {
                if (this.dataSource.find(m => m.subProjectId === item.subProjectId))
                    return item
            })
            if (obj)
                this.dataSource.splice(index, 1, {...obj, edit: false})
            else
                this.dataSource.splice(index, 1)
            this.amountChange()
        },
        editItem(index) {
            if (this.checkEditStatus()) return false
            this.dataSource[index]['edit'] = true
            this.activeIndex = index
            this.copyDataSource = JSON.parse(JSON.stringify(this.dataSource))
            this.$forceUpdate()
        },
        amountChange() {
            let amount = 0;
            this.dataSource.forEach(item => {
                if (!isNaN(item.subAmount) && !item.operation) {
                    amount = amount + item.subAmount
                }
            })
            this.dataSource[this.dataSource.length - 1]['subAmount'] = amount
            this.$forceUpdate()
        },
        addItem() {
            if (this.checkEditStatus()) return false
            const id = this.dataSource.length > 1 ? (this.dataSource[this.dataSource.length - 2].subProjectId || 0) / 1 + 1 : 1
            const obj = {subProjectId: id, subAmount: "", subDescription: "", edit: true}
            this.dataSource.splice(this.dataSource.length - 1, 0, obj)
        },
        removeItem(index) {
            const subDtos = this.dataSource[index]
            if (this.dataSource.length < 3) {
                this.$Message.error(this.$t('子项目不能为空'))
                return false;
            }
            if (this.$route.query.type !== 'add' && this.info.reSetSpecIn != 1) {
                const params = {
                    id: subDtos.id
                }
                this.axios({
                    method: 'get',
                    url: '/dms/capex/delSubItem',
                    params
                }).then(res => {
                    if (res.code === 200) {
                        this.$Message.success(res.msg)
                        location.reload()
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                })
            } else {
                if (this.info.reSetSpecIn == 1) {
                    this.isHandleSubProject = true
                }
                this.dataSource.splice(index, 1)
                this.amountChange()
            }


        },
        submitSubProject() {

            if (this.$route.query.type !== 'add' && this.info.reSetSpecIn != 1) {
                const obj = JSON.parse(JSON.stringify(this.dataSource[this.activeIndex]))
                obj.projectId = obj.subProjectId
                delete obj.edit


                if (this.$route.query.mainIdTag != 1 && this.$route.query.id) {
                    obj.turnToFirstSubItem = 1
                }

                const params = {
                    id: this.$route.query.id,
                    bdgAmount: this.form.bdgAmount,
                    subDtos: [obj],
                    reSetSpecIn: this.info.reSetSpecIn
                }


                this.axios({
                    method: 'post',
                    url: '/dms/capex/editSubItem',
                    data: params
                }).then(res => {
                    if (res.code === 200) {
                        this.dataSource[this.activeIndex]['edit'] = false
                        this.$Message.success(res.msg)
                        // this.$route.query.mainIdTag = 1
                        let mainInfo = {
                            path: this.$route.path,
                            query: {
                                ...this.$route.query,
                                mainIdTag: 1
                            }
                        }

                        const mainId = res.data;

                        if (mainId && mainId != null) {
                            mainInfo.query.id = mainId
                        }
                        this.$router.replace({
                            ...mainInfo
                        })
                        location.reload()
                        // this.$router.go(-1)
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                })
            } else {
                this.dataSource[this.activeIndex]['edit'] = false
            }
        },
        getForm(data) {
            const {
                projectId,
                projectName,
                projectType,
                companyId,
                specifications,
                businessCases,
                orgName,
                description,
                realname,
                projectOwnerStr,
                subDtos,
                includeSubProjects,
                estimatedROI,
                bdgAmount,
                estimatedBenefits,
                exceedsBudget,
                orgId,
                budgetReach,
                factoryOwner,
                factoryOwnerName,
                otherAttachments,
                companyName,
                cvEstimateds
            } = this.info;
            const {submitTime, submitByStr} = data;
            const companyObj = this.companyList.find(item => item.value === companyName / 1)

            this.form = Object.assign(this.form, {
                projectId,
                projectName,
                projectType,
                specifications,
                businessCases,
                companyName: (companyObj || {}).label,
                companyId: companyName / 1,
                orgName,
                description,
                submitTime,
                submitByStr,
                realname,
                projectOwnerStr,
                includeSubProjects,
                estimatedROI,
                bdgAmount,
                orgId,
                estimatedBenefits,
                exceedsBudget: Number(exceedsBudget),
                budgetReach,
                factoryOwner,
                factoryOwnerName,
                otherAttachments,
                whetherEstimatedBenefits: Array.isArray(cvEstimateds) && cvEstimateds.length > 0 ? 1 : 2
            })


            if (Array.isArray(subDtos))
                this.dataSource = [...subDtos, totalComlums]

            if (this.form.whetherEstimatedBenefits==1)
            {
                const value = this.calculatingBackRate(bdgAmount,cvEstimateds);
                this.form.returnOnInvestment = value
            }

            this.$forceUpdate()


            this.lastForm = JSON.parse(JSON.stringify(this.form))
            this.lastDataSource = JSON.parse(JSON.stringify(this.dataSource))
            this.userList = [
                {
                    id: factoryOwner,
                    realname: factoryOwnerName
                }
            ]
        },
        orgChange(val) {
            const {tag, value, label} = val
            this.form.orgId = value
            this.form.orgCode = tag
            this.form.orgName = label
        },
        async getParams() {
            const valid = await this.$refs.form.validate()
            let params = this.form

            if (params.includeSubProjects == 1) {
                if (this.checkEditStatus()) return false
            }

            if (params.includeSubProjects == 1 && this.dataSource.length < 2) {
                this.$Message.error(this.$t('子项目不能为空'))
                return;
            }

            if (params.whetherEstimatedBenefits == 1) {
                let cvEstimateds = this.$refs.estimatedRevenueTable.getParams();

                if (Array.isArray(cvEstimateds) && cvEstimateds.length > 0) {
                    cvEstimateds = cvEstimateds.map(item => {
                        const {estimatedTime, estimatedBenefits, remark} = item;
                        return {estimatedTime, estimatedBenefits, remark}
                    })

                    let total = 0;
                    for (let i = 0; i < cvEstimateds.length; i++) {
                        total = total + cvEstimateds[i].estimatedBenefits/1
                    }

                    params.estimatedBenefits = total


                    // if(total > this.form.bdgAmount){
                    //     this.$Message.error(this.$t('预计收益不能为空'))
                    //     return;
                    // }

                    // console.log(total)

                    params.cvEstimateds = cvEstimateds
                } else {
                    this.$Message.error(this.$t('预计收益不能为空'))
                    return false;
                }
                // return;
            }





            // params.actualROI = ((params.actualBenefits - params.bdgAmount) / params.bdgAmount * 100).toFixed(2)


            if (params.includeSubProjects == 1) {
                let list = JSON.parse(JSON.stringify(this.dataSource))
                list.splice(list.length - 1, 1)
                params.subDtos = []
                params.subDtos = list.map(item => {
                    const {
                        subAmount,
                        subDescription,
                        subProjectId,
                        id
                    } = item;
                    return {
                        subAmount,
                        subDescription,
                        subProjectId,
                        id
                    };
                })
            }


            /**
             * 比较数据是否发生
             */

            let isEdit = false
            if (this.lastForm.projectId) {
                const arrKey =
                    ["projectId",
                        "projectName",
                        "projectType",
                        "companyId",
                        "companyName",
                        "orgName",
                        "description",
                        "submitTime",
                        "submitByStr",
                        "realname",
                        "includeSubProjects",
                        "bdgAmount",
                        "orgId",
                        "estimatedBenefits",
                        "exceedsBudget",
                        "budgetReach",
                        "factoryOwner",
                        "projectOwnerStr",
                        "cvEstimateds"
                    ]

                for (let i = 0; i < arrKey.length; i++) {
                    if (this.lastForm[arrKey[i]] !== params[arrKey[i]]) {
                        isEdit = true
                    }
                }
            }

            if (this.isHandleSubProject)
                isEdit = true

            if (valid) {
                return {
                    ...params,
                    reSetSpecIn: isEdit ? 1 : 0,
                    rejectBidding: this.info.reSetSpecIn==1? 1:0
                }
            }
        }
    }
}
</script>

<style scoped lang="scss">
@import "./style";

/deep/ .ivu-input-number {
    width: 100% !important;
}

/deep/ .ivu-input-number-disabled .ivu-input-number-input {
    opacity: 1;
    background-color: #fff;
    color: #515a6e;
}

.ivu-table-cell-slot {
    text-align: left;

}

.exceed {
    color: rgb(252, 213, 63);
}

.tableInputNumberbr {
    border: 1px solid #dcdee2;

    /deep/ .ivu-input-number-input {
        border: none;
    }
}
</style>

